package wh.observers;

import java.util.Observable;
import java.util.Observer;
import wh.Manager;
import wh.Order;
import wh.ProcessedOrder;
import wh.UnProcessedOrder;
import wh.Worker;
import wh.exceptions.BadIDFormat;
import wh.exceptions.IDCollisionException;
import wh.exceptions.MissingReferenceException;
import wh.observabledata.OrderUpdateObject;

public class OrderUpdateObserver implements Observer {

	private Manager manager;
	
	public OrderUpdateObserver(Manager manager)
	{
		this.manager = manager;
	}
	
	@Override
	public void update(Observable arg, Object object) {
		
		if (object instanceof OrderUpdateObject) { // Graphic/UI update to let user know whats going on upon data change
			
			OrderUpdateObject updt = (OrderUpdateObject) object;
			
			Order order = updt.getOrder();
			
			int status = updt.getStatus();
			
			switch (status) 
	        {
				case Manager.STATUS_BEGIN_ORDER: 
					manager.highlightOrderProgress(order.getOrderID(), Manager.STATUS_BEGIN_ORDER, "", "", 
							order.getProductID(), order.getQuantity());
				break;
				
				case Manager.STATUS_UPDATE_ORDER: 
					String customerType = order.getCustomerType();
					double totalCost = order.getTotalCost();
					manager.highlightOrderProgress(order.getOrderID(), 
							Manager.STATUS_UPDATE_ORDER, customerType, ""+totalCost, order.getProductID(), order.getQuantity());
				break;
				
				case Manager.STATUS_FINISHED_ORDER: 
					
					ProcessedOrder processedOrder = (ProcessedOrder) updt.getUpdateOrder();
					
					manager.addProcessedOrder(processedOrder); // Done
					manager.addOrderToBeRemoved(order);
					
					manager.highlightOrderProgress(order.getOrderID(), Manager.STATUS_FINISHED_ORDER, "", "", 
							order.getProductID(), order.getQuantity());
					manager.checkIfProcessingIsDone(); // Checks if this thread is the last one
				break;
				
				case Manager.STATUS_FAILED_ORDER: 
					
					UnProcessedOrder unProOrder = (UnProcessedOrder) updt.getUpdateOrder();
					
				try {
					manager.addUnProcessedOrder(unProOrder);
				} catch (BadIDFormat e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IDCollisionException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (MissingReferenceException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
					manager.addOrderToBeRemoved(order);
					manager.highlightOrderProgress(order.getOrderID(), Manager.STATUS_FAILED_ORDER, "", "", 
							order.getProductID(), order.getQuantity());
					manager.checkIfProcessingIsDone();
					
				break;
	        }
		}
	}
}
